from django.shortcuts import render, redirect, HttpResponse
from django.http import JsonResponse
from .models import *
from datetime import datetime, timedelta
from collectcookiee.utils import check_cookie_status, user_info, get_article_title


# 获取cookie
def get_cookie(request):
    if request.method == 'POST':
        cookie = request.POST.get('cookie_content')
        user = user_info(cookie)
        print(user)
        if user:
            now_date = datetime.now()
            cookie = Cookies(cookie=cookie, status='1', last_update=now_date)
            cookie.save()
            usermess = UserMess()
            usermess.nick_name = user['nickname']
            usermess.profile = user['url']
            usermess.years = user['years']
            usermess.picture = user['avatarurl']
            usermess.tags = "|".join(user['model_list'])
            usermess.u_c = cookie
            usermess.save()
    return redirect('/')


# 返回首页
def cookie_view(request):
    remote_ip = request.META['REMOTE_ADDR']
    user_list = UserMess.objects.all()
    tasks = Tasks.objects.all()
    return render(request, 'index.html', locals())


# 添加 点赞评论 任务
def add_task(request):
    if request.method == 'POST':
        sender = request.POST.get('sender')
        article_url = request.POST.get('article_url')
        title = request.POST.get('title')
        release_time = datetime.now()
        finished_time = release_time + timedelta(minutes=5)  # 预计完成时间定为 5 分钟后
        status = '0'
        task = Tasks(
            sender=sender,
            title=title,
            article_url=article_url,
            release_time=release_time,
            finished_time=finished_time,
            status=status
        )
        task.save()
    return redirect('/')


# 获取文章标题
def article_title(request):
    result = {
        'title': ''
    }
    url = request.GET.get('article_url')
    if url:
        try:
            title = get_article_title(url)
            result['title'] = title
        except:
            pass
    return JsonResponse(result)


# 返回 Cookie 的借口
def send_cookie(requests):
    user_list = UserMess.objects.all()
    result = {}
    for item in user_list:
        result.update({
            item.nick_name: item.u_c.cookie
        })
    return JsonResponse(result)

# Create your views here.
